import Vue from 'vue';
import Router from 'vue-router';
import iview from 'iview';

import behindRouters from '@/pages/behind/router.js';
import frontRouter from '@/pages/front/router.js';

Vue.use(Router)

const router = new Router({
  //mode: 'history',
  routes: [
    ...frontRouter,
    ...behindRouters,
    {
      path: '/',
      name: '首页',
      meta: {
        menu: 0,
        requiresAuth: false
      },
      redirect: '/front/index'
    },
    {
      path: '/login',
      name: '登录',
      meta: {
        menu: 0,
        requiresAuth: false
      },
      component: resolve => require(['@/pages/login.vue'], resolve)
    },
    {
      path: '/register',
      name: '注册',
      meta: {
        menu: 0,
        requiresAuth: false
      },
      component: resolve => require(['@/pages/register.vue'], resolve)
    },
    {
      path: '/404',
      component: resolve => require(['@/components/NotFound.vue'], resolve)
    }
  ]
});

router.beforeResolve((to, from, next) => {
  const user = JSON.parse(window.sessionStorage.user || 'null');

  if (user) {
    router.app.$store.commit('logOn', user);
  }

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!user || !user.Name) {
      iview.Message.info('请登录！');
      return next({
        path: '/login',
        query: {
          redirect: to.fullPath
        }
      })
    } else {
      const rights = to.meta.rights || [];

      if (!rights.find(r => r == user.UserType)) {
        iview.Notice.warning({
          title: '警告',
          desc: '您没有使用该功能的权限，该功能由【' + router.app.$store.state.roles.get(rights[0]) + '】使用！'
        });

        return;
      }
    }
  }

  iview.LoadingBar.start();

  next() // 确保一定要调用 next()
});

router.afterEach(to => {
  window.scroll(0, 0);

  router.app.$nextTick(() => {
    if (to.meta && to.meta.menu != undefined) {
      let menus = document.querySelector('ul.nav').children;
      let current = menus[to.meta.menu];

      if (current) {
        Array.prototype.forEach.call(menus, function (e) {
          e.children[0].className = 'item-cn';
        });

        current.children[0].className = 'item-cn item-cn-active';
      }
    }

    if(to.meta && to.meta.leftMenu != undefined){
      let leftMenus = document.querySelector('div.left-nav > ul').children;

      if(leftMenus){
        Array.prototype.forEach.call(leftMenus, function(e){
          e.className = '';
        });

        let current = leftMenus[to.meta.leftMenu];

        if(current){
          current.className = 'active';
        }
      }
    }
  });

  iview.LoadingBar.finish();
});
export default router;
